package com.hn.birthdaymatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hn.birthdaymatch.constants.MessageConstant;
import com.hn.birthdaymatch.exception.BusinessException;
import com.hn.birthdaymatch.mapper.BirthdayMapper;
import com.hn.birthdaymatch.model.Birthday;
import com.hn.birthdaymatch.result.PageResult;
import com.hn.birthdaymatch.result.Result;
import com.hn.birthdaymatch.service.BirthdayService;
import com.hn.birthdaymatch.utils.SaltedEncryptionUtils;
import com.hn.birthdaymatch.utils.ValidateUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class BirthdayServiceImpl extends ServiceImpl<BirthdayMapper, Birthday> implements BirthdayService {

    @Override
    public PageResult<Birthday> findList(Map<String, Object> params) {
        //验证日期格式
        validateDate(
                MapUtils.getString(params, "year"),
                MapUtils.getString(params, "month"),
                MapUtils.getString(params, "day"),
                "SC");

        Page<Birthday> page = new Page<>(MapUtils.getInteger(params, "page", 1), MapUtils.getInteger(params, "limit"), 10);
        List<Birthday> list = baseMapper.findList(page, params);
        return PageResult.<Birthday>builder().data(list).code(0).count(page.getTotal()).build();
    }

    /**
     * 保存或者修改
     *
     * @param birthday
     * @return
     */
    @Override
    public Result saveOrUpdateRole(Birthday birthday) {
        validateDate
                (birthday.getYear(), birthday.getMonth(), birthday.getDay(), "");
        //判断保存或者修改
        if (birthday.getId() == null) {
            return saveBirthday(birthday) ? Result.succeed(MessageConstant.ADD_SUCCESS) : Result.failed(MessageConstant.ADD_FAILURE);
        } else {
            if (!ValidateUtils.isRequired(birthday.getUniIdentification())) {
                return Result.failed(MessageConstant.UNI_IDENTIFICATION_IS_NULL);
            }
            //查询匹配数据库，如果能够对上，则修改
            Birthday birthday1 = baseMapper.selectById(birthday.getId());
            if (birthday == null) {
                return Result.failed(MessageConstant.VERIFY_FAILURE);
            }
            if (!birthday.getUniIdentification().equals(SaltedEncryptionUtils.decrypt(birthday1.getUniIdentification()))) {
                return Result.failed(MessageConstant.UNI_IDENTIFICATION_ERROR);
            } else {
                return updateBirthday(birthday) ? Result.succeed(MessageConstant.UPDATE_SUCCESS) : Result.failed(MessageConstant.UPDATE_FAILURE);
            }
        }
    }


    private boolean saveBirthday(Birthday birthday) {
        //加密
        birthday.setUniIdentification(SaltedEncryptionUtils.encrypt(birthday.getUniIdentification()));
        birthday.setCreateTime(new Date());
        birthday.setStatus(0);
        return baseMapper.insert(birthday) > 0;
    }

    private boolean updateBirthday(Birthday birthday) {
        Birthday existingBirthday = baseMapper.selectById(birthday.getId());
        if (existingBirthday == null) {
            return false; // 如果记录不存在，则返回false
        }

        // 仅在字段非空时才进行更新
        if (birthday.getRealName() != null && !birthday.getRealName().isEmpty()) {
            existingBirthday.setRealName(birthday.getRealName());
        }
        if (birthday.getDay() != null && !birthday.getDay().isEmpty()) {
            existingBirthday.setDay(birthday.getDay());
        }
        if (birthday.getMonth() != null && !birthday.getMonth().isEmpty()) {
            existingBirthday.setMonth(birthday.getMonth());
        }
        if (birthday.getYear() != null && !birthday.getYear().isEmpty()) {
            existingBirthday.setYear(birthday.getYear());
        }
        if (birthday.getDyAccount() != null && !birthday.getDyAccount().isEmpty()) {
            existingBirthday.setDyAccount(birthday.getDyAccount());
        }
        birthday.setStatus(0);
        birthday.setUpdateTime(new Date());
        return baseMapper.updateById(existingBirthday) > 0;
    }

    @Override
    public Result verifyUniIdentification(Birthday birthday) {
        //查询匹配数据库，如果能够对上，则修改
        Birthday birthday1 = baseMapper.selectById(birthday.getId());
        if (birthday1 == null) {
            return Result.failed(MessageConstant.VERIFY_FAILURE);
        }
        if (birthday.getUniIdentification().equals(SaltedEncryptionUtils.decrypt(birthday1.getUniIdentification()))) {
            return Result.succeed(MessageConstant.VERIFY_SUCCESS);
        } else {
            return Result.failed(MessageConstant.UNI_IDENTIFICATION_ERROR);
        }
    }

    @Override
    public Result deleteBirthday(Map<String, Object> params) {
        Integer id = MapUtils.getInteger(params, "id");
        String uniIdentification = MapUtils.getString(params, "uniIdentification");
        //查询匹配数据库，如果能够对上，则修改
        Birthday birthday1 = baseMapper.selectById(id);
        if (birthday1 == null) {
            return Result.failed(MessageConstant.VERIFY_FAILURE);
        }
        if (uniIdentification.equals(SaltedEncryptionUtils.decrypt(birthday1.getUniIdentification()))) {
            Birthday birthday = new Birthday();
            birthday.setStatus(-1); // 设置你需要更新的字段
            int update = baseMapper.update(birthday, new LambdaUpdateWrapper<Birthday>().eq(Birthday::getId, id));
            if (update > 0) {
                return Result.succeed(MessageConstant.DELETE_SUCCESS);
            } else {
                return Result.failed(MessageConstant.DELETE_FAILURE);
            }
        } else {
            return Result.failed(MessageConstant.UNI_IDENTIFICATION_ERROR);
        }
    }

    /**
     * 验证输入的年月日是否有效
     *
     * @param year  年份字符串（可选）
     * @param month 月份字符串（可选）
     * @param day   日字符串（可选）
     * @param sc    特定的字符串参数用于额外的逻辑控制
     * @throws BusinessException 如果输入无效
     */
    public void validateDate(String year, String month, String day, String sc) throws BusinessException {
        try {
            // 当sc不等于"SC"时，要求年、月、日都不能为空
            if (!"SC".equals(sc)) {
                if (!StringUtils.hasText(year) || !StringUtils.hasText(month) || !StringUtils.hasText(day)) {
                    throw new BusinessException("年、月、日三个参数不能为空");
                }
            }
            Integer yr = (year != null && !year.equals("")) ? Integer.parseInt(year) : null;
            Integer mn = (month != null && !month.equals("")) ? Integer.parseInt(month) : null;
            Integer dy = (day != null && !day.equals("")) ? Integer.parseInt(day) : null;

            // 验证年份
            if (yr != null && (yr < 1900 || yr > 2099)) {
                throw new BusinessException("年份必须在1900到2099之间");
            }

            // 验证月份
            if (mn != null && (mn < 1 || mn > 12)) {
                throw new BusinessException("月份必须在1到12之间");
            }

            // 验证日期，只有当年份和月份都已提供时才验证日期
            if (yr != null && mn != null && dy != null) {
                int daysInMonth = getDaysInMonth(yr, mn);
                if (dy < 1 || dy > daysInMonth) {
                    throw new BusinessException("无效的日期，" + yr + "年的该月份没有" + dy + "天");
                }
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("日期必须为数字");
        }
    }

    private int getDaysInMonth(int year, int month) {
        switch (month) {
            case 2:
                return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            default:
                return 31;
        }
    }
}

